package com.hyl.interceptorbase.loginInterceprotphone;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyl.anno.login.Login;
import com.hyl.common.utils.RedisTools;
import com.hyl.pojo.erromessage.ErroMessage;
import com.hyl.pojo.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登入拦截器
 *
 * @author HYL
 * @create 2017-06-15 下午3:40
 **/
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    ErroMessage erroMessage;
    @Autowired
    private RedisTools redisTools;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Class<?> clazz = method.getDeclaringClass();
        if (clazz.isAnnotationPresent(Login.class)||method.isAnnotationPresent(Login.class)) {

            if (!isLogin(request)) {//需要验证登入，从缓存中获取用户看看是否为空
                 //用户未登入
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("status",2);
                jsonObject.put("message",erroMessage.erroStatusMessage.get(2));
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(jsonObject.toJSONString());
                return false;
            }else {
                return true;
            }

        }else {
            return true;
        }


    }
    /**
     * 查看用户是否登入
     */
    public boolean isLogin(HttpServletRequest request){
        String sessionId = request.getSession().getId();
        String value = redisTools.getValue(sessionId);
        if (value != null) {
            User user = JSON.parseObject(value, User.class);
            request.setAttribute("user",user);
            return true;
        }
        return false;
    }
}
